package com.bw.user.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import com.bw.user.entity.OrderInfoEntity;
import com.bw.user.service.OrderInfoService;
import com.bw.common.utils.PageUtils;
import com.bw.common.utils.R;


/**
 * 
 *
 * @author Hao_YunKai
 * @email 2745578447@qq.com
 * @date 2022-02-22 11:22:28
 */
@RestController
@RequestMapping("user/orderinfo")
public class OrderInfoController {
    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = orderInfoService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		OrderInfoEntity orderInfo = orderInfoService.getById(id);

        return R.ok().put("orderInfo", orderInfo);
    }

    // 通过秒杀接口隐藏id获取商品id
    @RequestMapping("getGoodsId/{pathId}")
    public String getGoodsId(@PathVariable("pathId") String pathId) {
        return redisTemplate.opsForValue().get(pathId);
    }

    /**
     * 保存  订单使用消息队列异步下单， 订单消息队列异步生成，为什么使用消息队列 (0.5天)
     */
    @RequestMapping("/save")
    @SentinelResource(value = "rule2", blockHandler = "exceptionHandler")
    public R save(@RequestBody OrderInfoEntity orderInfo){
        return orderInfoService.addOrder(orderInfo);
    }
    //  符合规则的降级处理方法
    public R exceptionHandler(@RequestBody OrderInfoEntity orderInfo, BlockException e){
        System.out.println("限流：" + e.getClass().getCanonicalName());
        return R.error("网络延迟");
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody OrderInfoEntity orderInfo){
		orderInfoService.updateById(orderInfo);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		orderInfoService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }
}
